package ilearning.demo.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Wang Xu
 * @date 2023/11/7
 */
@Configuration
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> List<String> getBeanNames(Class<T> clazz) {
        return Arrays.stream(applicationContext.getBeanNamesForType(clazz))
                .collect(Collectors.toList());
    }

    public static <T> List<NamedBean<T>> getAllBean(Class<T> clazz) {
        List<String> beanNames = getBeanNames(clazz);
        if (CollectionUtils.isEmpty(beanNames)) {
            return Collections.emptyList();
        }
        List<NamedBean<T>> beans = new ArrayList<>(beanNames.size());
        beanNames.forEach(bn -> new NamedBean<T>(bn, getBean(bn, clazz)));
        return beans;
    }

    public static class NamedBean<T> {
        private String beanName;

        private T bean;

        public String getBeanName() {
            return beanName;
        }

        public void setBeanName(String beanName) {
            this.beanName = beanName;
        }
        public T getBean() {
            return bean;
        }

        public void setBean(T bean) {
            this.bean = bean;
        }

        public NamedBean() {
        }

        public NamedBean(String beanName, T bean) {
            this.beanName = beanName;
            this.bean = bean;
        }
    }
}